<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\member\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\index\model\GetCityProper as GetCityProperModel;
use app\member\model\MemberStatus as MemberStatusModel;
use app\member\model\MemberAddress as MemberAddressModel;
use think\Db;

/**             
 * 行为管理控制器
 * @package app\admin\controller
 */
class Address extends Admin
{

    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        $map = $this->getMap();
        // 数据列表
        $data_list = MemberAddressModel::getAddressInfo($map);
        $is_default=MemberStatusModel::getIsDefault();
        foreach ($data_list as $key=>$values){
            $where['id']=$values['province'];
            $where['pid']=0;
            $where['status']=1;
            $province=GetCityProperModel::getPlace($where);
            $where1['pid']=$values['province'];
            $where1['id']=$values['city'];
            $where1['status']=1;
            $city=GetCityProperModel::getPlace($where1);
            $where2['pid']=$values['city'];
            $where2['id']=$values['area'];
            $where2['status']=1;
            $area=GetCityProperModel::getPlace($where2);
            $data_list[$key]['p_name']=$province['name'];
            $data_list[$key]['c_name']=$city['name'];
            $data_list[$key]['a_name']=$area['name'];
            $data_list[$key]['addr']=$province['name'].$city['name'].$area['name'].$values['address'];
        }
        // 分页数据
        $page = $data_list->render();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('收货地址管理')// 设置页面标题
            ->setTablename('member_address')// 设置数据表名
            ->setSearch(['consignee' => '收货人'])// 设置搜索参数
            ->setPrimaryKey('addr_id')
            ->addColumns([ // 批量添加列
                ['name', '会员姓名'],
                ['consignee', '收货人','','','','fix-table-td'],
                ['postcode', '邮政编码','','','','fix-table-td'],
                ['mobile', '手机号码','','','','fix-table-td'],
                ['tel', '固定电话','','','','fix-table-td'],
                ['addr', '收货地址','','','','fix-table-td'],
                ['is_default','默认地址','status','',$is_default],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add,delete')// 批量添加顶部按钮
            ->addRightButtons('edit',['href' => url('edit', ['addr_id' => '__id__'])])// 批量添加右侧按钮
            ->addRightButton('delete',['icon' => 'fa fa-times', 'title' => '删除', 'href' => url('delete_addr', ['addr_id' => '__id__'])])
            ->setRowList($data_list)// 设置表格数据
            ->setPages($page)// 设置分页数据
            ->fetch(); // 渲染页面
    }

    //新增收货地址
    public function add()
    {
        $list_province =Db::name("admin_area")->where("pid=0")->column("id,name");
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Address');
            // 验证失败 输出错误信息
            if (true !== $result) {
                return $this->error($result);
            }
            $member=$data['member_id'][0];
            $data['member_id']=$member;
            $res=Db::name('member_address')->insert($data);
            if ($res) {
                return $this->success('新增成功', cookie('__forward__'));
            } else {
                return $this->error('新增失败');
            }
        }
            // 使用ZBuilder快速创建表单
            return ZBuilder::make('form')
                ->setPageTitle('新增收货地址')// 设置页面标题
                ->addSelect('member_id','选择会员','','','','ajax','',['url'=>'/admin.php/member/Address/memberlist','datakey'=>'id','dataname'=>'name'])
                ->addFormItems([ // 批量添加表单项
                    ['static', '', ''],
                    ['text', 'consignee', '收货人'],
                    ['text','postcode', '邮政编码'],
                    ['text','mobile', '手机号码'],
                    ['text','tel', '固定电话'],
                    ['linkage', 'province', '选择省份','',$list_province,'',url('get_city'),'city,town'],
                    ['linkage', 'city', '选择城市','','','',url('get_area'),'town'],
                    ['select', 'area', '选择区域'],
                    ['text','address', '详细地址'],
                ])
                ->layout(['member_id'=>3,'consignee'=>3,'postcode'=>3,'mobile'=>3,'tel'=>3,'province'=>3,'area'=>3,'city'=>3,'address'=>6])
                ->fetch();
    }
    //编辑收货地址
    public function edit($id = null){
        $info = Db::name('member_address')->where('addr_id',$id)->find();
        $list_province =Db::name("admin_area")->where("pid=0")->column("id,name");
        $is_default=MemberStatusModel::getIsDefault();
        $member_id=$info['member_id'];
        $memberinfo=Db::name("member")->where("id",$member_id)->find();
        $arr = [];
        $arr[$memberinfo['id']] = $memberinfo['name'];
        $testid = $memberinfo['id'];
        if(!empty($info['province'])){
            $list_city = db("admin_area")->where("pid",$info['province'])->column("id,name");
            $list_area = db("admin_area")->where("pid",$info['city'])->column("id,name");
        }else{
            $list_city ='';
            $list_area ='';
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Address');
            // 验证失败 输出错误信息
            if (true !== $result) {
                return $this->error($result);
            }
            $member=$data['member_id'][0];
            $data['member_id']=$member;
            if($data['is_default']==1){
                $where['member_id']=$member_id;
                $where['addr_id']=array('neq',$id);
                $map['is_default']=0;
                Db::name('member_address')->update($data);
                $res=Db::name('member_address')->where($where)->update($map);
            }else{
                $res=Db::name('member_address')->update($data);
            }
            if ($res) {
                return $this->success('编辑成功', cookie('__forward__'));
            } else {
                return $this->error('编辑失败');
            }
        }
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('收货地址编辑')// 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden','addr_id'],
                ['select','member_id','选择会员','',$arr,$testid,'ajax','',['url'=>'/admin.php/member/Address/memberlist','datakey'=>'id','dataname'=>'name']],
                ['static', '', ''],
                ['text', 'consignee', '收货人'],
                ['text','postcode', '邮政编码'],
                ['text','mobile', '手机号码'],
                ['text','tel', '固定电话'],
                ['linkage', 'province', '选择省份','',$list_province,'',url('get_city'),'city,area'],
                ['linkage', 'city', '选择城市','',$list_city,'',url('get_area'),'area'],
                ['select', 'area', '选择区域','',$list_area],
                ['text','address', '详细地址'],
                ['static', '', ''],
                ['radio', 'is_default', '默认地址','',$is_default]
            ])
            ->setFormData($info) // 设置表单数据
            ->layout(['member_id'=>3,'consignee'=>3,'postcode'=>3,'mobile'=>3,'tel'=>3,'province'=>3,'area'=>3,'city'=>3,'address'=>6])
            ->fetch();
    }
    //单个删除
    public function delete_addr(){
        $id = $this->request->param('addr_id');
        $res=Db::name("member_address")->where('addr_id',$id)->delete();
        if ($res) {
            return $this->success('删除成功',cookie('__forward__'));
        } else {
            return $this->error('删除失败');
        }
    }
    //批量删除
    public function delete($record = [])
    {
        $ids        = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        foreach ($ids as $values){
            $res=Db::name("member_address")->where('addr_id',$values)->delete();
        }
        if ($res) {
            return $this->success('删除成功',cookie('__forward__'));
        } else {
            return $this->error('删除失败');
        }
    }
    public function get_city($province = '') {
        $result =Db::name("admin_area")->where("pid=$province")->field("id,name")->select();
        $list=[];
        foreach ($result as $key => $value) {
            # code...
            $list[$key]['key']=$value['id'];
            $list[$key]['value']=$value['name'];
        }

        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $arr['list'] = $list; //数据
        return json($arr);
    }

    public function get_area($city = '') {
        $result =Db::name("admin_area")->where("pid=$city")->field("id,name")->select();
        $list=[];
        foreach ($result as $key => $value) {
            # code...
            $list[$key]['key']=$value['id'];
            $list[$key]['value']=$value['name'];
        }

        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $arr['list'] = $list; //数据
        return json($arr);
    }
    //选择会员列表
    public function memberlist(){
        $search=input('q');
        $where['name']=['like',"%$search%"];
        $where['status']=1;
        $member=Db::name('member')->field('id,name')->where($where)->select();
        $memberlist=[];
        $a= 0;
        foreach($member as $value){
            $b = $a++;
            $key=$value['id'];
            $memberlist[$b]['id']=$key;
            $memberlist[$b]['name']=$value['name'];
        }
        return json(['items'=>$memberlist,'total_count'=>sizeof($memberlist)]);
    }
}